package utils;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;



public class ExcelParser {
    public static List<Student> parseExcelFile(File file) {
        List<Student> data = new ArrayList<>();
        try (FileInputStream fis = new FileInputStream(file)) {
            Workbook workbook = new XSSFWorkbook(fis);
            Sheet sheet = workbook.getSheetAt(0); // assuming the data is in the first sheet
            Row headerRow = sheet.getRow(0);
            int username=0,studentNumber = 0;
            // 这个if主要是寻找这个excel表的具体姓名和学号的具体列数
            if (headerRow != null) {
                int numCells = headerRow.getLastCellNum();
                for (int i = 0; i < numCells; i++) {
                    if (headerRow.getCell(i).getStringCellValue().equals("姓名")) {
                        username = i; //将姓名这一列赋值给 username
                    } else if (headerRow.getCell(i).getStringCellValue().equals("学号")) {
                        studentNumber=i;
                    }
                }
            }
            for (Row row : sheet) {
                if (!row.getCell(username).getStringCellValue().equals("姓名")){
                    Student student = new Student();
                    // 学号是数字类型，但因为超过int范围，将其转为double在转为long，再转string
                    double numericValue = row.getCell(studentNumber).getNumericCellValue();
                    long longValue = (long) numericValue;
                    student.setStudentNumber(String.valueOf(longValue));

                    student.setUsername(row.getCell(username).getStringCellValue());
                    data.add(student);
                }
            }
            workbook.close();
        } catch (Exception e) {
            List<Student> students = new ArrayList<>();
            Student student = new Student();
            student.setUsername("excel解析错误");
            student.setStudentNumber("500");
            students.add(student);
            return students;
        }
        return data;
    }
}
